﻿using Microsoft.Win32.SafeHandles;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.Record.Formula;
using ScannerApp.DataBase;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using XHD.Common;
using XHD.Model;
using XHD.View.WebService;

namespace XHD.CRM.webserver
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class CallBackSAS_For_MF : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            context.Response.ContentType = "text/plain";
            HttpRequest request = context.Request;
         
            if (request["Action"] == "UploadFile")
            {
                context.Response.ContentType = "text/plain";
                context.Response.Charset = "utf-8";

                var files = context.Request.Files;
                if (files.Count <= 0)
                {
                    return;
                }

                HttpPostedFile file = files[0];

                if (file == null)
                {
                    context.Response.Write("error|file is null");
                    return;
                }
                else
                {
                    string path = context.Server.MapPath("~/uploadedFiles/");  //存储图片的文件夹
                    string originalFileName = file.FileName;
                    string fileExtension = originalFileName.Substring(originalFileName.LastIndexOf('.'), originalFileName.Length - originalFileName.LastIndexOf('.'));
                    string currentFileName = (new Random()).Next() + fileExtension;  //文件名中不要带中文，否则会出错
                    //生成文件路径
                    if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
                    {
                        Directory.CreateDirectory(path);
                    }
                    string imagePath = path + currentFileName;
                    //保存文件
                    file.SaveAs(imagePath);
                    //返回图片url地址
                    context.Response.Write(currentFileName);
                    return;
                }
            }
            if (request["Action"] == "UploadFileArry")
            {
                context.Response.ContentType = "text/plain";
                context.Response.Charset = "utf-8";

                var files = context.Request.Files;
                if (files.Count <= 0)
                {
                    return;
                }

                string s = "";
                //foreach (HttpPostedFile file in files)
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFile file = files[i];

                    if (file == null)
                    {
                        s += ";" + "error|file is null";
                    }
                    else
                    {
                        string path = context.Server.MapPath("~/uploadedFiles/");  //存储图片的文件夹
                        string originalFileName = file.FileName;
                        string fileExtension = originalFileName.Substring(originalFileName.LastIndexOf('.'), originalFileName.Length - originalFileName.LastIndexOf('.'));
                        string currentFileName = (new Random()).Next() + fileExtension;  //文件名中不要带中文，否则会出错
                        if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
                        {
                            Directory.CreateDirectory(path);
                        }                                                           //生成文件路径
                        string imagePath = path + currentFileName;
                        //保存文件
                        file.SaveAs(imagePath);
                        //返回图片url地址
                        s += ";" + currentFileName;

                    }
                }
                context.Response.Write(s);
                return;
            }


            if (request["Action"] == "CallBackSASSingle")
            {
                //context.Request.ContentType = "multipart/form-data; charset=unicode";
                context.Response.ContentType = "text/plain";
                context.Response.Charset = "utf-8";
                string rstr = " {\"code\":-1,\"message\":\"faile\",\"data\":null}";
                try
                {
                    var files = context.Request.Files;
                    if (files.Count <= 0)
                    {
                        return;
                    }

                    HttpPostedFile file = files[0];

                    if (file == null)
                    {
                        context.Response.Write("error|file is null");
                        return;
                    }
                    else
                    {
                        string SASData =  (request["    "]);
                        
                        SAS_InfoDataEntity jcode = Common.StringToJson.DeserializeNew<SAS_InfoDataEntity>(SASData);
                        if (jcode == null)
                        {
                            rstr = " {\"code\":-1,\"message\":\"传入参数解析错误!\",\"data\":null}";
                            context.Response.Write(rstr);
                            return;
                        }
                        //  ScanAppSQLLogic.Insert_SAS_InfoData(jcode);
                        List<SAS_InfoImgDataEntity> imgs = new List<SAS_InfoImgDataEntity>();

                        string path = context.Server.MapPath("~/uploadedFiles/");  //存储图片的文件夹
                        string originalFileName = file.FileName;
                        string fileExtension = originalFileName.Substring(originalFileName.LastIndexOf('.'), originalFileName.Length - originalFileName.LastIndexOf('.'));
                        string currentFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_1"  + fileExtension;  //文件名中不要带中文，否则会出错
                        path = path + jcode.casereference + "/";                                                            //生成文件路径
                        if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
                        {
                            Directory.CreateDirectory(path);
                        }
                        string imagePath = path + currentFileName;

                        //   var a = request.Form["base64"];
                        //  string err = Base64StringToImage(a.Replace("data:image/png;base64,", "").Replace("data:image/jpeg;base64,", ""), imagePath);
                        //保存文件
                        file.SaveAs(imagePath);
                        SAS_InfoImgDataEntity en = new SAS_InfoImgDataEntity();
                        en.orgin_Name = originalFileName;
                        en.img_Name = jcode.casereference + "/"+currentFileName;
                        en.createtime = DateTime.Now;
                        en.casereference = jcode.casereference;
                        imgs.Add(en);
                        var r = ScanAppSQLLogic.Insert_SAS_InfoData(jcode, imgs);
                        if (!r.Item1)
                        {
                            rstr = " {\"code\":-1,\"message\":\"保存数据错误!" + r.Item2 + "\",\"data\":null}";
                            context.Response.Write(rstr);
                            return;
                        }
                        var rx = ScanAppSQLLogic.Get_SAS_InfoData(jcode.casereference);
                       if(!rx.Item1) {
                            rstr = " {\"code\":-1,\"message\":\"" + rx.Item2 + "\",\"data\":null}";
                        }
                        else
                        {
                            SAS_MFEntity MFentity=new SAS_MFEntity();
                            string upmsg = UploadMF("ShXxSperm", jcode, imgs);
                            if (upmsg != "") rstr = " {\"code\":-1,\"message\":\"" + rx.Item2+ upmsg + "\",\"data\":null}";
                            else
                            {
                                object obj = new
                                {
                                    MainData = rx.Item3,
                                    FileData = imgs
                                };
                                rstr = " {\"code\":0,\"message\":\"success\",\"data\":\"" + Common.StringToJson.SerializeObject(obj) + "\"}";
                            }
                                //返回图片url地址
                            context.Response.Write(rstr);
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    rstr = " {\"code\":-1,\"message\":\"" + ex.Message + "\",\"data\":null}";
                    context.Response.Write(rstr);
                    return;
                }
            }




            if (request["Action"] == "CallBackSASMutliple")
            {
                //context.Request.ContentType = "multipart/form-data; charset=unicode";
                context.Response.ContentType = "text/plain";
                context.Response.Charset = "utf-8";
                string rstr = " {\"code\":-1,\"message\":\"faile\",\"data\":null}";
                try
                {
                    var files = context.Request.Files;
                    if (files.Count <= 0)
                    {
                        rstr = " {\"code\":-1,\"message\":\"无文件!\",\"data\":null}";
                        context.Response.Write(rstr);
                        return;
                    }
                    string SASData = request["SASData"] ; 
                
                    SAS_InfoDataEntity jcode = Common.StringToJson.DeserializeNew<SAS_InfoDataEntity>(SASData);
                    jcode.collector = Regex.Unescape(jcode.collector);
                    jcode.Operator = Regex.Unescape(jcode.Operator);
                    Common.StringToJson.WriteLogToFileDiffTable(SASData,jcode.casereference);
                    if (jcode == null)
                    {
                        rstr = " {\"code\":-1,\"message\":\"传入参数解析错误!\",\"data\":null}";
                        context.Response.Write(rstr);
                        return;
                    }
                    if (jcode.casereference == null || jcode.casereference == "")
                        jcode.casereference ="Auto"+ DateTime.Now.ToString("yyMMddHHmmss");
                    //if (!ScanAppSQLLogic.ExistDoc(jcode.casereference))
                    //{
                    //    rstr = " {\"code\":-1,\"message\":\"" + jcode.casereference + "此单据不在可分析状态!\",\"data\":null}";
                    //    context.Response.Write(rstr);
                    //    return;
                    //}
                    List<SAS_InfoImgDataEntity> imgs = new List<SAS_InfoImgDataEntity>();

                    string s = "";
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile file = files[i];

                        if (file == null)
                        {
                            s += ";" + "error|file is null";
                        }
                        else
                        {
                            string path = context.Server.MapPath("~/uploadedFiles/");  //存储图片的文件夹
                            string originalFileName = file.FileName;
                            string fileExtension = originalFileName.Substring(originalFileName.LastIndexOf('.'), originalFileName.Length - originalFileName.LastIndexOf('.'));
                            string currentFileName = DateTime.Now.ToString("yyyyMMddHHmmssffff")+"_"+i + fileExtension;  //文件名中不要带中文，否则会出错
                            path = path + jcode.casereference + "/";
                            if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
                            {
                                Directory.CreateDirectory(path);
                            }                                                           //生成文件路径
                            string imagePath = path + currentFileName;
                            //保存文件
                            file.SaveAs(imagePath);
                            //返回图片url地址
                            s += ";" + currentFileName;
                            SAS_InfoImgDataEntity en = new SAS_InfoImgDataEntity();
                            en.orgin_Name = currentFileName;
                            en.img_Name = imagePath;// jcode.casereference + "/"+currentFileName;
                            en.createtime = DateTime.Now;
                            en.casereference = jcode.casereference;
                            imgs.Add(en);
                        }
                    }
                    var r = ScanAppSQLLogic.Insert_SAS_InfoData_ForMF(jcode, imgs);
                    if (!r.Item1)
                    {
                        rstr = " {\"code\":-1,\"message\":\"保存数据错误!" + r.Item2 + "\",\"data\":null}";
                        context.Response.Write(rstr);
                        return;
                    }

                    var rx = ScanAppSQLLogic.Get_SAS_InfoData(jcode.casereference);
                    if (!rx.Item1)
                    {
                        rstr = " {\"code\":-1,\"message\":\"" + rx.Item2 + "\",\"data\":null}";
                    }
                    else
                    {
                         
                        string upmsg = UploadMF("ShXxSperm", jcode, imgs);
                        if (upmsg != "") rstr = " {\"code\":-1,\"message\":\"" + rx.Item2 + upmsg + "\",\"data\":null}";
                        else
                        {
                            object obj = new
                            {
                                code = 0,
                                message = "success",
                                data = new
                                {
                                    MainData = rx.Item3,
                                    FileData = imgs
                                }
                            };
                            rstr = Common.StringToJson.ObjectToJson(obj);//" {\"code\":0,\"message\":\"success\",\"data\":\"" + Common.StringToJson.ObjectToJson(obj) + "\"}";
                        }
                            //返回图片url地址
                        context.Response.Write(rstr);
                        return;
                    }
                   

                }
                catch (Exception ex)
                {
                    rstr = " {\"code\":-1,\"message\":\"" + ex.Message + "\",\"data\":null}";
                    context.Response.Write(rstr);
                    return;
                }
            }


        }
        //base64编码的文本 转为    图片
        private string Base64StringToImage(string base64string, string path)
        {
            try
            {
                byte[] bt = Convert.FromBase64String(base64string);
                File.WriteAllBytes(path, bt);
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string UploadMF(string apiFun, SAS_InfoDataEntity sasEntity, List<SAS_InfoImgDataEntity> listImg) {

            try
            {
                SAS_MFEntity entity = SmartDataTableExtensions.ConvertModel<SAS_MFEntity, SAS_InfoDataEntity>(sasEntity);
                 
                entity.vbatch = sasEntity.batchnumber==null?sasEntity.casereference: sasEntity.batchnumber;
                entity.tcheckoutDate = StringPlus.str2date( sasEntity.date); 
                entity.voperator = sasEntity.Operator;
                entity.vtype = sasEntity.sperm;
                //下面三个放默认值
                entity.vcheckoutTime = DateTime.Now.ToString(); ;
                entity.bstandard = true;
                entity.vresult = "OK";

                entity.ddensity = StringPlus.str2dec( sasEntity.totmml.ToString());
                entity.dvitality = StringPlus.str2dec(sasEntity.motpercen.ToString());
                entity.icopies = sasEntity.produceddosis??0;
                entity.dadd = StringPlus.str2dec(sasEntity.diluentvolume.ToString());
                entity.dcapacity = sasEntity.dosisvolume ?? 0;
                entity.dmilliliter = StringPlus.str2dec(sasEntity.ejaculatedvolume.ToString());
                entity.dmotileSperms = sasEntity.usefulspermperdosis ?? 0;
                entity.dmalformation = StringPlus.str2dec(sasEntity.totalspermsperdosis.ToString());
                //20240809增加
                entity.iTotalNum = sasEntity.totnumber ?? 0;
                entity.iNormalNum = sasEntity.nornumber ?? 0;
                entity.dNormalRatio = sasEntity.norpercen ?? 0;
                entity.dNear = sasEntity.pronumber ?? 0;
                entity.dFastForw = sasEntity.rapnumber ?? 0;
                entity.dAnnular = sasEntity.cirnumber ?? 0;
                entity.dPlaceMove = sasEntity.locnumber ?? 0;
                entity.dInactive = sasEntity.immnumber ?? 0;
                entity.dTailBend = sasEntity.bennumber ?? 0;
                entity.dEndRoll = sasEntity.coinumber ?? 0;
                entity.dDMR = sasEntity.dmrnumber ?? 0;
                entity.dFar = sasEntity.disnumber ?? 0;
                entity.iMalformaNum = sasEntity.malnumber ?? 0;
                entity.dMalformaRatio = sasEntity.malpercen ?? 0;
                entity.dForwVitality = sasEntity.prognumber ?? 0;
                entity.progpercen = sasEntity.progpercen ?? 0;
                entity.dSlowForw = sasEntity.slonumber ?? 0;
                 


                //
                SAS_MF_mxlistEntity mxEntity = new SAS_MF_mxlistEntity();
                mxEntity.vgzgp = sasEntity.subject;
                mxEntity.vpz = sasEntity.breed;
                //不知道
                mxEntity.tcsrq = DateTime.Now;// StringPlus.str2date("1900-01-01");//DateTime.Now;
                mxEntity.vpx = sasEntity.strain;
                List<SAS_MF_mxlistEntity> listMX = new List<SAS_MF_mxlistEntity>();
                listMX.Add(mxEntity);
                entity.mxlist = listMX;

                string url =ConfigHelper.GetConfigString("APIUrl") + apiFun ;
               // string filePath = @"C:\Users\huazha01\OneDrive\图片\alarmtimes.png";
                string appkey = ConfigHelper.GetConfigString("appkey");//"7492D92B81024810D757D87A4702BF01";
                string deviceId = ConfigHelper.GetConfigString("deviceId");//"MYJCN1D009Y17";
                
                    //"[{\"vbatch\":\"LOT20240221001\",\"tcheckoutDate\":\"2024-02-21\",\"vcheckoutTime\":\"10:12\",\"voperator\":\"张三\",\"wtype\":\"鲜精\",\"ddensity\":213.48,\"dvitality\":94.55,\"icopies\":12,\"dadd\":632,\"vresult\":\"757\",\"dcapacity\":60,\"dmilliliter\":125,\"dmotileSperms\":2000,\"dmalformation\":2115.06,\"bstandard\":true,\"vfile\":[{\"vtpmc\":\"DD1234-C1-1\",\"vfile\":\"category-a.png\"}],\"mxlist\":[{\"vgzgP\":\"DD1234\",\"tcsrq\":\"2021-01-02\",\"vpz\":\"DD\",\"vpx\":\"美系\"}]}]";
                 NameValueCollection nvcfile = new NameValueCollection();
                List<SAS_MF_VFileEntity> listfile = new List<SAS_MF_VFileEntity>();
                listMX.Add(mxEntity);
                string postFiles = "";int ix = 1;
                foreach (SAS_InfoImgDataEntity efile in listImg)
                {
                    nvcfile.Add(efile.orgin_Name, efile.img_Name);
                    SAS_MF_VFileEntity fileEntity = new SAS_MF_VFileEntity();
                    fileEntity.vtpmc = "槽"+ix;
                    fileEntity.vfile = efile.orgin_Name;
                    listfile.Add(fileEntity);
                    postFiles += "&file=" + efile.img_Name;
                    ix++;
                }
                entity.vfile = listfile;

                NameValueCollection nvc1 = new NameValueCollection();
                nvc1.Add("appkey", appkey);
                nvc1.Add("deviceId", deviceId);
                string strdata = AppApiUtils.Serialize(entity);
                nvc1.Add("data", "["+strdata+"]");

                string postfile = HttpUtility.UrlEncode(postFiles.Substring(1) + "&appkey=" + appkey + "&deviceId=" + deviceId + "&data=" + strdata);

                var head = new Dictionary<string, string>
                                {
                                { "Method", "POST" },
                                { "ContentType", "application/x-www-form-urlencoded; charset=UTF-8" }
                                };
                string rest = comm.PostMultipartFormData(url, head, nvc1, nvcfile);
                JObject jo = AppApiUtils.DataToJObject(rest);
                if (rest == "{\"status\":true}")
                    return "";
                else return jo["msg"].ToString();
            }catch(Exception ex)
            {

                return ex.Message;
            }
        }
        /*
         * application/x-www-form-urlencoded; charset=UTF-8
         * file: C:\fakepath\Blue.png
appkey: 7492D92B81024810D757D87A4702BF01
deviceId: MYJCN1D009Y17
data: [{"vbatch":"LOT20240221001","tcheckoutDate":"2024-02-21","vcheckoutTime":"10:12","voperator":"张三","wtype":"鲜精","ddensity":213.48,"dvitality":94.55,"icopies":12,"dadd":632,"vresult":"757","dcapacity":60,"dmilliliter":125,"dmotileSperms":2000,"dmalformation":2115.06,"bstandard":true,"vfile":[{"vtpmc":"DD1234-C1-1","vfile":"category-a.png"}],"mxlist":[{"vgzgP":"DD1234","tcsrq":"2021-01-02","vpz":"DD","vpx":"美系"}]}]

         file=C%3A%5Cfakepath%5CBlue.png&appkey=7492D92B81024810D757D87A4702BF01&deviceId=MYJCN1D009Y17&data=%5B%7B%22vbatch%22%3A%22LOT20240221001%22%2C%22tcheckoutDate%22%3A%222024-02-21%22%2C%22vcheckoutTime%22%3A%2210%3A12%22%2C%22voperator%22%3A%22%E5%BC%A0%E4%B8%89%22%2C%22wtype%22%3A%22%E9%B2%9C%E7%B2%BE%22%2C%22ddensity%22%3A213.48%2C%22dvitality%22%3A94.55%2C%22icopies%22%3A12%2C%22dadd%22%3A632%2C%22vresult%22%3A%22757%22%2C%22dcapacity%22%3A60%2C%22dmilliliter%22%3A125%2C%22dmotileSperms%22%3A2000%2C%22dmalformation%22%3A2115.06%2C%22bstandard%22%3Atrue%2C%22vfile%22%3A%5B%7B%22vtpmc%22%3A%22DD1234-C1-1%22%2C%22vfile%22%3A%22category-a.png%22%7D%5D%2C%22mxlist%22%3A%5B%7B%22vgzgP%22%3A%22DD1234%22%2C%22tcsrq%22%3A%222021-01-02%22%2C%22vpz%22%3A%22DD%22%2C%22vpx%22%3A%22%E7%BE%8E%E7%B3%BB%22%7D%5D%7D%5D
         */
    }
}